package com.warmlight.voicepacket.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.umeng.analytics.MobclickAgent;
import com.warmlight.voicepacket.Add2ListActivity;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.base.MBaseAdapter;
import com.warmlight.voicepacket.data.PlaydeatalData;
import com.warmlight.voicepacket.data.RecommendFeed;
import com.warmlight.voicepacket.data.SearchResult;
import com.warmlight.voicepacket.data.TempData;
import com.warmlight.voicepacket.data.eventbus.PlayerServiceData;
import com.warmlight.voicepacket.data.eventbus.ShareUnlock;
import com.warmlight.voicepacket.dbmanager.DBFloatPlayListDetailDaoHelp;
import com.warmlight.voicepacket.fragment.CopyShareFragment;
import com.warmlight.voicepacket.fragment.CustomBottomSheetDialogFragment;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.ui.Add2NetListActivity;
import com.warmlight.voicepacket.utils.JSONUtils;
import com.warmlight.voicepacket.utils.MobClickHelper;
import com.warmlight.voicepacket.utils.SPUtils;
import com.warmlight.voicepacket.utils.StringUtils;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import okhttp3.Call;

import static com.warmlight.voicepacket.data.eventbus.PlayerServiceData.PAUSE;
import static com.warmlight.voicepacket.data.eventbus.PlayerServiceData.PLAY;
import static com.warmlight.voicepacket.db.VoicePacketDBHelper.AUDIO_ID;

/**
 * 搜索 音频adapter
 */
public class SearchAdapter extends MBaseAdapter<SearchResult.DataBean.AudioListBean> {

    private String mSearchKey = "";
    private boolean isLogin = false;

    public SearchAdapter(Context context, List list) {
        super(context, list);
        if (SPUtils.isLogined()){
            isLogin = true;
        }else{
            isLogin = false;
        }
    }



    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder = null;
        if (convertView == null){
            convertView = LayoutInflater.from(mContext).inflate(R.layout.view_search_media,parent,false);
            viewHolder = new ViewHolder();
            viewHolder.iv_search_love = (ImageView) convertView.findViewById(R.id.iv_search_love);
            viewHolder.iv_search_play = (ImageView) convertView.findViewById(R.id.iv_search_play);
            viewHolder.iv_search_share = (ImageView) convertView.findViewById(R.id.iv_search_share);
            viewHolder.tv_cover = (TextView) convertView.findViewById(R.id.tv_cover);
            viewHolder.tv_title = (TextView) convertView.findViewById(R.id.tv_title);
            viewHolder.iv_search_lock = (ImageView) convertView.findViewById(R.id.iv_search_lock);
            convertView.setTag(viewHolder);
        }else{
            viewHolder = (ViewHolder) convertView.getTag();
        }

        final SearchResult.DataBean.AudioListBean item = getItem(position);
        String cover_name = item.getCover_name();
        String title = item.getTitle();
        final String url = item.getUrl();
        final int play = item.getPlay();
        final String is_share = item.getIs_share();
        final String is_unlocked = item.getIs_unlocked();

        viewHolder.tv_cover.setText(cover_name);

        if ("1".equals(is_share) && "0".equals(is_unlocked)){
            //需要解锁
            viewHolder.iv_search_lock.setVisibility(View.VISIBLE);

        }else{
            viewHolder.iv_search_lock.setVisibility(View.GONE);

        }

        if (1 == play){//播放
            viewHolder.iv_search_play.setImageResource(R.drawable.icon_playing_new);
            viewHolder.tv_title.setTextColor(Color.parseColor("#CE3838"));
            viewHolder.tv_title.setText(title);
        }else if (2==play){//暂停
            viewHolder.iv_search_play.setImageResource(R.drawable.icon_pause_new);
            viewHolder.tv_title.setTextColor(Color.parseColor("#CE3838"));
            viewHolder.tv_title.setText(title);
        }else{//正常
            if ("1".equals(is_share) && "0".equals(is_unlocked)){
                viewHolder.iv_search_play.setImageResource(R.drawable.icon_playdetal_lock);
            }else{
                viewHolder.iv_search_play.setImageResource(R.drawable.icon_playdetal);
            }
//            viewHolder.iv_search_play.setImageResource(R.drawable.icon_playdetal);
            viewHolder.tv_title.setTextColor(Color.parseColor("#333333"));
            SpannableString spannableString = StringUtils.changeTextColor(Color.parseColor("#7b2aff"), title, mSearchKey);
            viewHolder.tv_title.setText(spannableString);
        }
        if (isLogin){
            boolean is_collect = item.isIs_collect();
            if (is_collect) {
                viewHolder.iv_search_love.setImageResource(R.drawable.icon_fav_y);
            } else {
                viewHolder.iv_search_love.setImageResource(R.drawable.icon_shoucangdeep);
            }
        }else {
            boolean exists = DBFloatPlayListDetailDaoHelp.isExists(mContext, item.getId());
            if (exists) {
                viewHolder.iv_search_love.setImageResource(R.drawable.icon_fav_y);
            } else {
                viewHolder.iv_search_love.setImageResource(R.drawable.icon_shoucangdeep);
            }
        }
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(is_share) && "0".equals(is_unlocked)){
                    //需要解锁
                    //如果有锁就去跳转分享
                    SearchResult.DataBean.AudioListBean.ShareInfoBean share = item.getShare_info();
                    PlaydeatalData.DataBean.ShareBean shareBean = new PlaydeatalData.DataBean.ShareBean();
                    shareBean.setDesc(share.getDesc());
                    shareBean.setH5_url(share.getH5_url());
                    shareBean.setPic_url(share.getPic_url());
                    shareBean.setTitle(share.getTitle());
                    new CustomBottomSheetDialogFragment(shareBean, new CustomBottomSheetDialogFragment.ShareCallBack() {
                        @Override
                        public void shareSuccess(boolean isSuccess) {
                            shareResult(isSuccess,item.getCover_id(),position);
                        }
                    },true).show(((FragmentActivity)mContext).getSupportFragmentManager(), "search");
                }else{

                    if (1 == play){
                        item.setPlay(2);
                        EventBus.getDefault().post(new PlayerServiceData(PAUSE,url));
                    }else if (2==play){
                        item.setPlay(1);
                        EventBus.getDefault().post(new PlayerServiceData(PLAY,url));
                    }else{
                        clearPlay();
                        item.setPlay(1);
                        EventBus.getDefault().post(new PlayerServiceData(PLAY,url));

                        MobclickAgent.onEvent(mContext.getApplicationContext(), MobClickHelper.s_BAG_FEED_PLAY, item.getTitle());
                        HashMap<String, Object> temp = new HashMap<>();
                        temp.put("网络播单", item.getTitle());
                        ZhugeSDK.getInstance().track(mContext.getApplicationContext(),MobClickHelper.s_BAG_FEED_PLAY, temp);

                    }
                    notifyDataSetChanged();
                }


            }
        });

        viewHolder.iv_search_share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(is_share) && "0".equals(is_unlocked)){
                    //需要解锁
                    //如果有锁就去跳转分享
                    SearchResult.DataBean.AudioListBean.ShareInfoBean share = item.getShare_info();
                    PlaydeatalData.DataBean.ShareBean shareBean = new PlaydeatalData.DataBean.ShareBean();
                    shareBean.setDesc(share.getDesc());
                    shareBean.setH5_url(share.getH5_url());
                    shareBean.setPic_url(share.getPic_url());
                    shareBean.setTitle(share.getTitle());
                    new CustomBottomSheetDialogFragment(shareBean, new CustomBottomSheetDialogFragment.ShareCallBack() {
                        @Override
                        public void shareSuccess(boolean isSuccess) {
                            shareResult(isSuccess,item.getCover_id(),position);
                        }
                    },true).show(((FragmentActivity)mContext).getSupportFragmentManager(), "search");
                }else {

                    android.support.v4.app.FragmentManager fragmentManager = ((FragmentActivity) mContext).getSupportFragmentManager();
                    new CopyShareFragment().show(fragmentManager, "Dialog");//展示分享弹窗
                    TempData.AudioData = changeBean(item);

                    //网络播单
                    MobclickAgent.onEvent(mContext,MobClickHelper.s_BAG_FEED_SHARE, item.getTitle());
                    HashMap<String, Object> temp = new HashMap<>();
                    temp.put("网络播单分享", item.getTitle());
                    ZhugeSDK.getInstance().track(mContext, MobClickHelper.s_BAG_FEED_SHARE, temp);
                }
            }
        });

        viewHolder.iv_search_love.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if ("1".equals(is_share) && "0".equals(is_unlocked)){
                    //需要解锁
                    //如果有锁就去跳转分享
                    SearchResult.DataBean.AudioListBean.ShareInfoBean share = item.getShare_info();
                    PlaydeatalData.DataBean.ShareBean shareBean = new PlaydeatalData.DataBean.ShareBean();
                    shareBean.setDesc(share.getDesc());
                    shareBean.setH5_url(share.getH5_url());
                    shareBean.setPic_url(share.getPic_url());
                    shareBean.setTitle(share.getTitle());
                    new CustomBottomSheetDialogFragment(shareBean, new CustomBottomSheetDialogFragment.ShareCallBack() {
                        @Override
                        public void shareSuccess(boolean isSuccess) {
                            shareResult(isSuccess,item.getCover_id(),position);
                        }
                    },true).show(((FragmentActivity)mContext).getSupportFragmentManager(), "search");
                }else {
                    RecommendFeed.DataBean.ListBean bean = new RecommendFeed.DataBean.ListBean();

                    bean.setDuration(item.getDuration());
                    bean.setCategory_id(item.getCategory_id());
                    bean.setId(item.getId());
                    bean.setCollect(item.getCollect());
                    bean.setShare(item.getShare());
                    bean.setStar(item.getStar());
                    bean.setTitle(item.getTitle());
                    bean.setUrl(item.getUrl());
                    bean.setCover_pic(item.getCover_pic());
                    bean.setCover_id(item.getCover_id());
                    bean.setCover_name(item.getCover_name());
                    if (SPUtils.isLogined()){
                        Intent addIntent = new Intent(mContext, Add2NetListActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(AUDIO_ID, bean);
                        addIntent.putExtras(bundle);
                        mContext.startActivity(addIntent);
                    }else{
                        Intent addIntent = new Intent(mContext, Add2ListActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(AUDIO_ID, bean);
                        addIntent.putExtras(bundle);
                        mContext.startActivity(addIntent);
                    }



                    //网络播单
                    MobclickAgent.onEvent(mContext,MobClickHelper.s_BAG_FEED_CLOT, item.getTitle());
                    HashMap<String, Object> temp = new HashMap<>();
                    temp.put("网络播单收藏", item.getTitle());
                    ZhugeSDK.getInstance().track(mContext,MobClickHelper.s_BAG_FEED_CLOT, temp);
//
                }
            }
        });

        return convertView;
    }

    private void shareResult(boolean isSuccess, final String id, final int position){
        if (isSuccess) {
            TreeMap<String,String> map = new TreeMap<>();
            map.put("audio_id",id);
            map.put("type","2");
            HttpClient.post(HttpConfig.SERVER + HttpConfig.SHARE, map, new com.warmlight.voicepacket.http.Callback() {
                @Override
                public void onFailure(Call call, IOException e) {

                }

                @Override
                public void onResponse(Call call, String response) {
//                    String string = response.body().string();
                    ArrayList<Map<String, String>> listMapByJson = JSONUtils.getListMapByJson(response);
                    if (listMapByJson.size()>0){
                        Map<String, String> map1 = listMapByJson.get(0);
                        if ("200".equals(map1.get("code"))){
                            EventBus.getDefault().post(new ShareUnlock(false,position,id));
//                            mList.get(position).setUnlockSuccess(true);
                        }
                    }
                }
            });
        }
    }

    private RecommendFeed.DataBean.ListBean changeBean(SearchResult.DataBean.AudioListBean temp){
        RecommendFeed.DataBean.ListBean bean = new RecommendFeed.DataBean.ListBean();
        bean.setTitle(temp.getTitle());
        bean.setId(temp.getId());
        bean.setUrl(temp.getUrl());
        bean.setDuration(temp.getDuration());
        bean.setStar(temp.getStar());
        bean.setShare(temp.getShare());
        bean.setCollect(temp.getCollect());
        bean.setCover_id(temp.getCover_id());
        return bean;
    }

    public void setSearchKey(String mSearchKey) {
        this.mSearchKey = mSearchKey;
    }

    public void clearPlay() {
        for (int j = 0;j<mList.size();j++){
            mList.get(j).setPlay(0);
        }
        notifyDataSetChanged();
    }

    public void updata(boolean islist, int item, String cover_id){
        for (int i=0;i<getCount();i++){
            SearchResult.DataBean.AudioListBean item1 = getItem(i);
            if (item1.getCover_id().equals(cover_id)){
                item1.setIs_unlocked("1");
            }
        }
        notifyDataSetChanged();
    }

    public void notifyCollect(String audioId) {
        if (isLogin){
            for (int j = 0;j<mList.size();j++){
                SearchResult.DataBean.AudioListBean audioListBean = mList.get(j);
                String id = audioListBean.getId();
                if (TextUtils.equals(audioId,id)){
                    audioListBean.setIs_collect(true);
                    break;
                }

            }
        }else{

        }
        notifyDataSetChanged();
    }


    static class ViewHolder{
        ImageView iv_search_play;
        TextView tv_title;
        TextView tv_cover;
        ImageView iv_search_share;
        ImageView iv_search_love;
        ImageView iv_search_lock;
    }

}
